package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.xuanzheng.company.entity.Company;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.CompanyService;
import com.xuanzheng.company.service.impl.CompanyServiceImpl;
import com.xuanzheng.company.dao.UserDao;
import com.xuanzheng.company.dao.impl.UserDaoImpl;
import com.xuanzheng.company.dao.CompanyEmployeeDao;
import com.xuanzheng.company.dao.impl.CompanyEmployeeDaoImpl;
import com.xuanzheng.company.entity.CompanyEmployee;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/admin/getCompanyDetail")
public class GetCompanyDetailServlet extends HttpServlet {
    private final CompanyService companyService = new CompanyServiceImpl();
    private final UserDao userDao = new UserDaoImpl();
    private final CompanyEmployeeDao companyEmployeeDao = new CompanyEmployeeDaoImpl();
    private final Gson gson = new Gson();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            String companyId = request.getParameter("companyId");
            
            // 打印调试信息
            System.out.println("GetCompanyDetailServlet - 请求参数: companyId=" + companyId);
            
            if (companyId == null || companyId.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "公司ID不能为空");
            } else {
                Company company = companyService.getCompanyById(companyId);
                
                // 打印调试信息
                System.out.println("GetCompanyDetailServlet - 查询结果: company=" + (company != null ? company.getId() : "null"));
                
                if (company == null) {
                    result.put("success", false);
                    result.put("message", "公司不存在");
                } else {
                    Map<String, Object> companyDetail = new HashMap<>();
                    companyDetail.put("id", company.getId());
                    companyDetail.put("name", company.getName());
                    companyDetail.put("address", company.getAddress());
                    companyDetail.put("phone", company.getPhone());
                    companyDetail.put("creditCode", company.getCreditCode());
                    companyDetail.put("employeeCount", company.getEmployeeCount());
                    companyDetail.put("status", company.getStatus());
                    companyDetail.put("createTime", company.getCreateTime());
                    
                    // 获取负责人详细信息
                    User manager = userDao.findById(company.getManagerId());
                    
                    // 打印调试信息
                    System.out.println("GetCompanyDetailServlet - 负责人: " + (manager != null ? manager.getId() : "null"));
                    
                    if (manager != null) {
                        Map<String, Object> managerInfo = new HashMap<>();
                        managerInfo.put("id", manager.getId());
                        managerInfo.put("name", manager.getName());
                        managerInfo.put("phone", manager.getPhone());
                        managerInfo.put("email", manager.getEmail());
                        managerInfo.put("gender", manager.getGender());
                        managerInfo.put("age", manager.getAge());
                        companyDetail.put("manager", managerInfo);
                    }
                    
                    try {
                        // 获取公司员工信息摘要
                        List<CompanyEmployee> activeEmployees = companyEmployeeDao.getActiveEmployeesByCompanyId(companyId);
                        
                        // 打印调试信息
                        System.out.println("GetCompanyDetailServlet - 员工数量: " + (activeEmployees != null ? activeEmployees.size() : "null"));
                        
                        Map<String, Object> employeeSummary = new HashMap<>();
                        employeeSummary.put("total", activeEmployees != null ? activeEmployees.size() : 0);
                        
                        // 按部门统计人数
                        Map<String, Integer> departmentCount = new HashMap<>();
                        
                        if (activeEmployees != null && !activeEmployees.isEmpty()) {
                            for (CompanyEmployee employee : activeEmployees) {
                                String department = employee.getDepartment();
                                if (department == null || department.trim().isEmpty()) {
                                    department = "未分配部门";
                                }
                                
                                departmentCount.put(department, departmentCount.getOrDefault(department, 0) + 1);
                            }
                        }
                        
                        if (departmentCount.isEmpty()) {
                            departmentCount.put("未分配部门", 0);
                        }
                        
                        employeeSummary.put("departmentCount", departmentCount);
                        companyDetail.put("employeeSummary", employeeSummary);
                    } catch (Exception e) {
                        // 如果获取员工信息出错，提供一个空的摘要
                        System.out.println("GetCompanyDetailServlet - 获取员工信息出错: " + e.getMessage());
                        e.printStackTrace();
                        
                        Map<String, Object> employeeSummary = new HashMap<>();
                        employeeSummary.put("total", 0);
                        employeeSummary.put("departmentCount", new HashMap<>());
                        companyDetail.put("employeeSummary", employeeSummary);
                    }
                    
                    result.put("success", true);
                    result.put("company", companyDetail);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "获取公司详情失败：" + e.getMessage());
        }
        
        // 打印最终返回的JSON
        String jsonResult = gson.toJson(result);
        System.out.println("GetCompanyDetailServlet - 返回JSON: " + jsonResult);
        
        out.write(jsonResult);
        out.flush();
    }
} 